package org.example;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class MySQLDemo {
    public static void main(String[] args) {
        //mysql连接参数
        String mysqlDriver = "com.mysql.cj.Driver";
        String url = "jdbc:mysql://localhost:3306/redisdemo";
        String username = "root";
        String password = "";
        //创建连接、执行sql语句的对象
        Connection conn = null;
        PreparedStatement ps = null;
        try{
            //加载驱动
            Class.forName(mysqlDriver);
            conn= DriverManager.getConnection(url, username, password);
            ps = conn.prepareStatement("select * from student");
            ResultSet rs = ps.executeQuery();//执行查询
            while(rs.next()){
                System.out.print("id:"+rs.getInt("id")+",");
                System.out.print("name:"+rs.getString("name")+",");
                System.out.print("age:"+rs.getInt("age")+",");
                System.out.print("score:"+rs.getFloat("score")+",");
                System.out.println();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                if(ps != null){ps.close();}
            }catch (Exception ex1){
                ex1.printStackTrace();
            }
            try {
                if(conn != null){
                    conn.close();
                }
            }
            catch (Exception ex2){
                ex2.printStackTrace();
            }
        }
    }
}
